<template>
	<div>
		<!--搜索弹窗-->
		<search-model ref="searchModel" class="tab-search">
			<div class="textleft">
				<label for="">公告内容</label>
				<input type="text" v-model="contentdatatext" />
			</div>
			<div class="textleft">
				<label for="">创建时间</label>
				<span>
				    <el-date-picker v-model="startTimeStrtext" :date="startTimeStrtext" type="datetime" placeholder="选择日期时间" style="width: 145px;">
				    </el-date-picker>
			    </span>
				<!--<input type="text" v-model="startTimeStrtext" class="control-label" style="width:35%" />-->
				<label for="">到</label>
				<span>
				    <el-date-picker v-model="endTimeStrtext" :date="endTimeStrtext" type="datetime" placeholder="选择日期时间" style="width: 145px;">
				    </el-date-picker>
			    </span>
				<!--<input type="text" v-model="endTimeStrtext" style="width:35%;margin-right: 20px;" />-->
			</div>
			<!--<label for="">创建人</label>
			<input type="text" name="" class="control-label" style="width: 30%;margin-right: 40px;" />-->
			<div class="textleft">
				<label for="">状态</label>
				<select v-model="statustext" style="width: 30%;">
					<option value="-1">全部</option>
					<option value="1">已上线</option>
					<option value="0">已下线</option>
					<option value="2">已过期</option>
				</select>
			</div>

			<div style="text-align: center;clear: both;">
				<search-button text="搜索" :clickEvent="searchbuttonEvent"></search-button>
				<gray-button text="取消" :clickEvent="hideModel" class="cancelBtn"></gray-button>
			</div>
		</search-model>

		<blue-button text="高级搜素" :clickEvent="searchClickEvent" class="add-btn2"></blue-button>
		<blue-button text="新增" :clickEvent="addClickEvent" class="add-btn1"></blue-button>
		<table class="notice sv-table">
			<tr class="table-th">
				<th>编号</th>
				<th>公告标题</th>
				<th>公告内容</th>
				<th>创建日期</th>
				<th>生效日期</th>
				<th>状态</th>
				<th>创建人</th>
				<th>操作</th>
			</tr>
			<tr class="table-tr" v-for="(item, index) in getDataArray" :key="index">
				<td>{{index+1}}</td>
				<td>{{item.title}}</td>
				<td v-html="item.content"></td>
				<td>{{item.createTm | Time}}</td>
				<td><span>{{item.showDateFrom | Time}}</span> -- <span>{{item.showDateTo | Time}}</span></td>
				<td>{{statedata(item)}}</td>
				<!--item.status == "0" ? "已下线" : "已上线"-->
				<td>{{item.createUserName}}</td>
				<td class="handle-button" ref="handleButton">
					<gray-button :disabled="statedata(item)=='已过期'" :text="item.status == '0' ? '上线' : '下线'" :clickEvent="enableClickEvent.bind(this, item.rid, item.status,statedata(item))"></gray-button>
					<gray-button text="编辑" :disabled="item.status == '1'" :clickEvent="editClickEvent.bind(this, index,item.status)"></gray-button>
					<gray-button text="删除" :clickEvent="deleteClickEvent.bind(this, item.rid)"></gray-button>
				</td>
			</tr>
		</table>
		<mo-paging v-if="dataArray" :page-index="currentPage" :total="Arraycount" :page-size="pageSize" @change="pageChange">
		</mo-paging>
		<!-- 编辑或新增的弹框 -->
		<edit-model ref="editModel" title="新增公告">
			<div class="slot-notice" slot="main" style="max-height: 75vh;overflow-y: auto;" id="scrollOuter">
				<div class="textleft">
					<label for="">公告标题<span class="required">*</span></label>
					<input type="text" style="width: 100%;" placeholder="16个汉字以内" v-model="getDataItem.title" />
				</div>
				<div class="textleft">
					<label for="">图片上传</label>
					<!--<span class="required">*</span>-->
					<div class="upload-box">
						<img-upload ref="bannerImg" :deleteCallback="deleteImgCallback" :imgShowList="getBannerUrl ? [getBannerUrl] : []">
						</img-upload>
					</div>

				</div>
				<div class="textleft">
					<label for="">公告内容<span class="required">*</span></label>
					<div ref="noticeEditor">
					</div>
				</div>
				<div class="textleft" style="margin-top: 10px;">
					<label for="">生效日期</label>
					<span>
						<el-date-picker v-model="startTime" :date="startTime" type="datetime" placeholder="选择日期时间">
						</el-date-picker>
					</span>
					<label for="">到</label>
					<span>
						<el-date-picker v-model="endtime" :date="endtime" type="datetime" placeholder="选择日期时间">
						</el-date-picker>
					</span>
				</div>
				<!--<div class="textleft">
					<label for=""><span class="required">*</span>使用状态</label>
					<input style="width: 5%;" type="radio" name="tuiguang" checked @click="changeType(1)" />启用
					<input style="width: 5%;" type="radio" name="tuiguang" @click="changeType(2)" />禁用
				</div>-->
				<div class="fabu-box noticebutton">
					<blue-button text="提交" :clickEvent="submitClickEvent"></blue-button>
				</div>
			</div>
		</edit-model>
		<m-toast ref="toast"></m-toast>
		<m-dialog ref="dialog"></m-dialog>
	</div>
</template>

<script>
	import BlueButton from "../../../edit-components/BlueButton";
	import pagination from "../../../edit-components/pagination";
	import SearchButton from "../../../edit-components/SearchButton";
	import GrayButton from "../../../edit-components/GrayButton";
	import EditModel from "../../../edit-components/EditModel";
	import SearchModel from "../../../edit-components/SearchModel";
	import Toast from "../../../edit-components/Toast";
	import Dialog from "../../../edit-components/Dialog";
	import WangEditor from "WangEditor";
	import getData from './getData';
	import enabledBulletin from "./enabledBulletin";
	import publish from "./editOAdd";
	import deleteFn from "./delete";
	import add from "./add";
	import { DatePicker } from "element-ui";
	import imgUpload from "../../../real-components/ImgUpload2";
	//	import 'element-ui/lib/theme-chalk/index.css'
	export default {
		data() {
			return {
				dataArray: [],
				dataItem: null,
				handleType: "add",
				editor: null,
				params: {},
				type: 1,
				contentdata: "",
				startTime: "",
				endtime: "",
				contentdatatext: '',
				startTimeStrtext: '',
				endTimeStrtext: '',
				statustext: -1,
				imgUrl: '',
				getBannerUrl: null,
				//分页
				pageSize: 5, //每页显示20条数据
				currentPage: 1, //当前页码
				count: 0, //总记录数
				storeCode: ""
			}
		},
		components: {
			"blue-button": BlueButton,
			"mo-paging": pagination,
			"search-button": SearchButton,
			"gray-button": GrayButton,
			"edit-model": EditModel,
			"search-model": SearchModel,
			"el-date-picker": DatePicker,
			"m-toast": Toast,
			"m-dialog": Dialog,
			"img-upload": imgUpload,
		},
		computed: {
			getDataArray() {
				console.log("this.dataArray", this.dataArray)
				return this.dataArray;
			},
			//获得选中的数据item
			getDataItem() {
				if(this.dataItem) {
					return this.dataItem;
				}
				return {};
			},
			Arraycount() {
				return this.count;
			}
		},
		methods: {
			getShopCode() {
				this.storeCode = localStorage.getItem("storeCode");
			},
			//初始化表格数据
			getNoticeData() {
				let params = {
					length: this.pageSize,
					pageNum: this.currentPage,
					start: (this.currentPage - 1) * this.pageSize,
					storeId: this.storeCode
				}
				let callback = (data) => {
					this.dataArray = data.results;
					this.count = data.totalCount
				}
				getData(callback, params);
			},
			pageChange(page) {
				this.currentPage = page
				this.getNoticeData()
			},
			//停用/启用按钮的事件
			enableClickEvent(rid, status, statusdata) {
				if(statusdata == "已过期") {
					return
				}
				let msg = status == "0" ? "上线" : "下线";
				let msgss = `确定要${msg}该公告内容吗？`;
				let toastmsg1 = `该公告${msg}成功`;
				let toastmsg2 = `该公告${msg}失败`;
				let confirmFn = () => {
					status = status == "1" ? "0" : "1";
					let params2 = {
						length: this.pageSize,
						pageNum: this.currentPage,
						start: (this.currentPage - 1) * this.pageSize,
						storeId: this.storeCode
					}
					let params = {
						rid,
						status,
					}
					let callback = data => {
						this.dataArray = data.results;
						this.count = data.totalCount
						this.$refs.toast.toast(toastmsg1);
					}
					let errFn = (data) => {
						this.$refs.toast.toast(toastmsg2);
					}
					enabledBulletin(params, callback, params2, errFn);
				}
				this.infoDialog(msgss, confirmFn);
			},
			//删除按钮的事件
			deleteClickEvent(id) {
				let msg = "删除不可恢复，您确定要继续么？";
				let confirmFn = () => {
					let params2 = {
						length: this.pageSize,
						pageNum: this.currentPage,
						start: (this.currentPage - 1) * this.pageSize,
						storeId: this.storeCode
					}
					let params = id
					let callback = data => {
						this.dataArray = data.results;
						this.count = data.totalCount;
						this.$refs.toast.toast("删除成功");
					}
					let errFn = (data) => {
						this.$refs.toast.toast(data);
					}
					deleteFn(params, callback, params2, errFn);
				}
				this.infoDialog(msg, confirmFn);
			},
			//新增按钮的事件
			addClickEvent() {
				if(!getCookie("sessionId")){
				this.$refs.toast.toast("登录失效，请重新登录");
				return
			    }
				this.handleType = "add";
				this.$refs.editModel.showCover();
				// let item = this.getDataItem(index);
				this.dataItem = {};
				this.imgUrl = '';
				this.getBannerUrl = '';
				this.$refs.bannerImg.deleteImg();
				this.startTime = "";
				this.endtime = "";
				this.editor.txt.html("<p><br></p>")
				var node = document.getElementById("scrollOuter");
				setTimeout(() => {
					if(node) node.scrollTop = 0;
				}, 300);
			},
			//高级搜索按钮事件
			searchClickEvent() {
				this.$refs.searchModel.showCover();
				this.contentdatatext = '';
				this.startTimeStrtext = '';
				this.endTimeStrtext = '';
				this.statustext = -1;
			},
			//高级搜索取消按钮
			hideModel() {
				this.$refs.searchModel.hideCover()
			},
			//搜索按钮事件
			searchbuttonEvent() {
				let startdate = new Date(this.startTimeStrtext);
				let enddate = new Date(this.endTimeStrtext);
				let startdatetime = this.startTimeStrtext ? `${startdate.getFullYear()}-${startdate.getMonth() + 1}-${startdate.getDate()} ${startdate.getHours()}:${startdate.getMinutes()}:${startdate.getSeconds()}` : ""
				let enddatetime = this.endTimeStrtext ? `${enddate.getFullYear()}-${enddate.getMonth() + 1}-${enddate.getDate()} ${enddate.getHours()}:${enddate.getMinutes()}:${enddate.getSeconds()}` : ""
				let params = {}
				this.dataArray = []
				params = {
					length: this.pageSize,
					pageNum: this.currentPage,
					start: (this.currentPage - 1) * this.pageSize,
					content: this.contentdatatext,
					startTimeStr: startdatetime,
					endTimeStr: enddatetime,
					status: this.statustext,
					storeCode: 0,
					storeId: this.storeCode
				}
				let callback = (data) => {
					this.dataArray = data.results;
					this.count = data.totalCount
					/*console.log("消息公告的配置数据", this.dataArray);*/
				}
				getData(callback, params);

				this.$refs.searchModel.hideCover();
			},
			//编辑按钮的事件
			editClickEvent(index, status) {
				if(status == 1) {
					return
				}
				this.$refs.editModel.showCover();
				this.handleType = "edit";
				this.dataItem = this.getDataItemFn(index);
				//图片渲染
				this.getBannerUrl = this.dataItem.imgUrl;
				this.imgUrl = this.dataItem.imgUrl;
				//初始化生效开始时间
				this.startTime = this.dataItem.showDateFrom;
				//初始化生效结束时间
				this.endtime = this.dataItem.showDateTo;
				//富文本编辑器内容
				this.editor.txt.html(this.dataItem.content)
			},
			//发布按钮的点击事件
			async submitClickEvent() {
				let response = await this.$refs.bannerImg.upload();
				if(response.status === 1) {
					this.imgUrl = response.data[0];
				}
				/*if(response.status === 0) {
					this.errorToast("图片上传失败");
					return;
				}
				if(response.status === 2) {
					this.errorToast("请上传图片");
					return;
				}*/
				this.publishFn();
			},
			//获取校验规则
			publishFn() {
				this.getParams()
				//校验公告标题
				if(!this.params.title) {
					this.$refs.toast.toast("公告标题不能为空");
					return;
				}
				if(this.params.title.length > 16) {
					this.$refs.toast.toast("公告标题长度不能超过16个汉字");
					return;
				}
				//校验公告内容
				if(this.params.content == "<p><br></p>") {
					this.$refs.toast.toast("公告内容不能为空");
					return;
				}
				//校验生效开始日期
				/*if(!this.startTime) {
					this.$refs.toast.toast("生效开始日期不能为空");
					return;
				}*/
				//校验生效结束日期
				/*if(!this.endtime) {
					this.$refs.toast.toast("生效结束日期不能为空");
					return;
				}*/
				//开始日期不能大于结束日期
				if(!this.startTime && !this.startTime && this.startTime > this.endtime) {
					this.$refs.toast.toast("开始日期不能大于结束日期");
					return;
				}
				let params2 = {
					length: this.pageSize,
					pageNum: this.currentPage,
					start: (this.currentPage - 1) * this.pageSize,
					storeId: this.storeCode
				}
				let callback = (data) => {
					this.$refs.toast.toast("发布成功");
					this.dataArray = data.results;
					this.count = data.totalCount;
					this.$refs.editModel.hideCover();
				}
				let errFn = (data) => {
					this.$refs.toast.toast(data);
				}
				if(this.handleType === "edit") {
					publish(this.params, callback, params2, errFn);
				} else if(this.handleType === "add") {
					add(this.params, callback, params2, errFn);
				}
			},
			//参数格式化
			getParams() {
				/*let storeId = localStorage.getItem("shopId");*/
				this.contentdata = this.editor.txt.html();
				let startdate = new Date(this.startTime);
				let enddate = new Date(this.endtime);
				let startdatetime = this.startTime ? `${startdate.getFullYear()}-${startdate.getMonth() + 1}-${startdate.getDate()} ${startdate.getHours()}:${startdate.getMinutes()}:${startdate.getSeconds()}` : ""
				let enddatetime = this.endtime ? `${enddate.getFullYear()}-${enddate.getMonth() + 1}-${enddate.getDate()} ${enddate.getHours()}:${enddate.getMinutes()}:${enddate.getSeconds()}` : ""
				this.params = {
					rid: "",
					storeId: this.storeCode,
					imgUrl: this.imgUrl,
					showDateFromStr: startdatetime,
					showDateToStr: enddatetime,
					content: this.contentdata,
					title: this.getDataItem.title,
				}
				if(this.handleType == "edit") {
					this.params = Object.assign({}, this.params, {
						rid: this.getDataItem.rid,
					});
				}
				console.log("这是要上传的params", this.params);
			},
			//启用禁用type
			changeType(type) {
				this.type = type;
			},
			//返回对应index的数据
			getDataItemFn(index) {
				return this.dataArray[index];
			},
			//返回状态上下线状态
			statedata(item) {
				var timestamp1 = new Date(item.showDateTo)
				var timestamp2 = new Date()
				if(item.showDateTo && timestamp1 < timestamp2) {
					return "已过期"
				} else if(item.status == 0) {
					return "已下线"
				} else if(item.status == 1) {
					return "已上线"
				}
			},
			//初始化富文本
			initNoticeEditor() {
				this.editor = new WangEditor(this.$refs.noticeEditor)
				this.editor.customConfig.menus = [
					'head', // 标题
					'bold', // 粗体
					'italic', // 斜体
					'underline', // 下划线
					'strikeThrough', // 删除线
					'foreColor', // 文字颜色
					'backColor', // 背景颜色
					'link', // 插入链接
					'image', // 插入图片
					'list', // 列表
					'justify', // 对齐方式
					'quote', // 引用
					'emoticon', // 表情
					'undo', // 撤销
					'redo' // 重复
				];
				this.editor.customConfig.uploadImgServer = window.api.mall_file_host+"/upload";
				// 将图片大小限制为 10M
				this.editor.customConfig.uploadImgMaxSize = 10 * 1024 * 1024;
				this.editor.customConfig.uploadImgHooks = {
					customInsert: function(insert, result, noticeEditor) {
						if(result.code == 200) {
							var url = result.visitPath;
							insert(url)
						} else {
							layer.msg("上传图片失败!");
						}
					}
				}
				this.editor.change = function() { // 这里是change 不是官方文档中的 onchange
					// 编辑区域内容变化时，实时打印出当前内容
					this.contentdata = this.txt.html()
				}

				this.editor.create()
				/*this.editor.txt.html('<p>输入内容...</p>')*/
			},
			//确认弹框
			infoDialog(msg, confirmFn) {
				this.$refs.dialog.dialog({
					msg,
					confirmFn
				});
			},
			deleteImgCallback() {
				this.imgUrl = '';
			}
		},
		filters: {
			Time: function(time) {
				if(time) {
					let date = new Date(time);
					// return date.getFullYear() + "-" + date.getMonth() + "-";
					return `${date.getFullYear()}-${date.getMonth() + 1 > 9 ? date.getMonth() + 1:'0' + (date.getMonth() + 1)}-${date.getDate()}  ${date.getHours() > 9 ? date.getHours() : '0' + date.getHours()}:${date.getMinutes() > 9 ? date.getMinutes() : '0' + date.getMinutes()}`;
				}
			}
		},
		created() {
			this.getShopCode()
			this.getNoticeData()
		},
		mounted() {
			if(!getCookie("sessionId")){
				this.$refs.toast.toast("登录失效，请重新登录");
			}
			this.initNoticeEditor()
			/*this.$nextTick(() => {
				
			})*/
		},
	}
</script>

<style>
	.tab-search {
		float: left;
		white-space: nowrap;
		display: table;
	}
	
	.tab-search input,
	.tab-search label,
	.tab-search select {
		width: inherit;
		display: inline-block;
	}
	
	.tab-search input,
	.tab-search select {
		border: 1px solid #ddd;
		padding: 5px 5px;
		/*width: 50%;*/
		height: unset;
		margin-bottom: 20px;
	}
	
	.tab-search label {
		display: inline-block;
		/*width: 60px;*/
		text-align: left;
		margin-top: 5px;
		margin-bottom: 10px;
	}
	
	.add-btn1,
	.add-btn2 {
		display: inline-block;
		margin-bottom: 10px;
	}
	
	.add-btn1 {
		float: left;
	}
	
	.add-btn2 {
		float: right;
	}
	
	.notice span.sdrag-gray-btn.disabled {
		opacity: 1;
		color: #676767 !important;
	}
	
	.notice .handle-button span.sdrag-gray-btn {
		border: none;
		line-height: 40px;
		background: none;
		color: #3876af;
		width: 50px;
	}
	
	.required {
		vertical-align: sub;
		display: inline-block;
		margin-left: 0.5rem;
		color: #e74c3c;
	}
	
	.textleft {
		text-align: left;
	}
	
	.noticebutton .sdrag-blue-btn {
		display: inline-block;
	}
	
	.cancelBtn {
		display: inline-block;
		margin-left: 20px;
	}
	
	.tab-search .el-input__prefix,
	.el-input__suffix {
		height: auto;
	}
	
	.notice tr td:nth-child(3) {
		width: 120px;
		display: inline-block;
		height: 66px;
		overflow: hidden;
		line-height: 66px;
		border: none
	}
	/*上传图片*/
	
	.slot-notice .upload-box {
		border: 1px solid #ddd;
		display: inline-block;
		vertical-align: middle;
		margin-top: 10px;
	}
</style>